import { BasicColumn, FormSchema } from '/@/components/Table';
import { Ref } from 'vue';
import { DescItem } from '/@/components/Description';

export const columns: BasicColumn[] = [
  {
    title: '用户名',
    dataIndex: 'username',
    width: 120,
  },
  {
    title: '用户姓名',
    dataIndex: 'realname',
    width: 120,
  },
  {
    title: '电话',
    dataIndex: 'phone',
    width: 120,
  },
  {
    title: '部门',
    dataIndex: 'orgCodeTxt',
    width: 200,
  },
  {
    title: '状态',
    dataIndex: 'status_dictText',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
  },
];

export const searchFormSchema: FormSchema[] = [
  {
    field: 'username',
    label: '用户名',
    component: 'Input',
    colProps: { span: 8 },
  },
  {
    field: 'realname',
    label: '用户姓名',
    component: 'Input',
    colProps: { span: 8 },
  },
];

// 基本信息form
export function useBaseInfoForm(treeData: Ref<any[]>) {
  const descItems: DescItem[] = [
    {
      field: 'departName',
      label: '机构名称',
    },
    {
      field: 'parentId',
      label: '上级部门',
      render(val) {
        if (val) {
          const data = findTree(treeData.value, (item) => item.key == val);
          return data?.title ?? val;
        }
        return val;
      },
    },
    {
      field: 'orgCode',
      label: '机构编码',
    },
    {
      field: 'orgCategory',
      label: '机构类型',
      render(val) {
        if (val === '1') {
          return '公司';
        } else if (val === '2') {
          return '部门';
        } else if (val === '3') {
          return '岗位';
        }
        return val;
      },
    },
    {
      field: 'departOrder',
      label: '排序',
    },

    {
      field: 'mobile',
      label: '手机号',
    },
    {
      field: 'address',
      label: '地址',
    },
    {
      field: 'memo',
      label: '备注',
    },
  ];

  return { descItems };
}
/**
 * 查找树结构
 * @param treeList
 * @param fn 查找方法
 * @param childrenKey
 */
export function findTree(treeList: any[], fn: Fn, childrenKey = 'children') {
  for (let i = 0; i < treeList.length; i++) {
    const item = treeList[i];
    if (fn(item, i, treeList)) {
      return item;
    }
    const children = item[childrenKey];
    if (isArray(children)) {
      const findResult = findTree(children, fn, childrenKey);
      if (findResult) {
        return findResult;
      }
    }
  }
  return null;
}

export function isArray(val: any): val is Array<any> {
  return val && Array.isArray(val);
}
